<!-- 加班列表 -->
<template>
  <ContainerLayout class="overitem-list">
    <div class="form-container">
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <el-form-item label="用户">
          <el-input v-model="queryForm.user" clearable placeholder="请输入" style="width: 150px" />
        </el-form-item>
        <el-form-item label="部门">
          <el-cascader :options="deptList" :props="deptProps" style="width: 290px" v-model="queryForm.deptIds" collapse-tags clearable />
        </el-form-item>
        <el-form-item label="项目">
          <el-select v-model="queryForm.projectId" placeholder="请选择项目" clearable style="width: 160px">
            <el-option v-for="item in projectList" :key="item.code" :label="`${item.code}-${item.cname}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.overtimeStatus" placeholder="请选择状态" clearable style="width: 130px">
            <el-option v-for="item in overtimeStatusOptions" :key="item.value" :label="`${item.label}`" :value="item.value" />
          </el-select>
        </el-form-item>
        <TimeSlotDatePicker label="时段" v-model="queryForm.date" />
        <el-form-item>
          <el-button type="primary" @click="handleClickBtnSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="button-toolbar">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-space wrap :size="20">
            <el-switch v-model="isHistoryData" size="small" active-text="历史" inactive-text="审批" />
            <el-button plain size="small" type="success" @click="handleClickBtnUpdateOvertimeStatus(overtimeStatusEnum.部门领导通过)" :icon="Select">批量通过</el-button>
            <el-button plain size="small" type="danger" @click="handleClickBtnUpdateOvertimeStatus(overtimeStatusEnum.已驳回)" :icon="CloseBold">批量不通过</el-button>
            <ExcelExportButton :headerParams="exportHeaderParams" :table-data="exportTableData" fileName="加班部门审核" />
          </el-space>
        </el-col>
      </el-row>
    </div>
    <div class="table-container">
      <div class="table-wrap" ref="tableWrap">
        <el-table :data="tableData" @selection-change="handleSelectionChange" scrollbar-always-on style="width: 100%" border :height="tableHeight" header-cell-class-name="table-header-row" empty-text="没有数据">
          <el-table-column type="selection" :selectable="selectable" width="55" fixed />
          <el-table-column prop="deptName" label="部门" width="120" fixed v-if="false" />
          <el-table-column prop="userNick" label="姓名" width="150" fixed />
          <el-table-column label="项目" show-overflow-tooltip width="250">
            <template #default="scope">
              {{ getProjectName(scope.row.projectId) }}
            </template>
          </el-table-column>

          <el-table-column label="时段">
            <el-table-column label="开始时间" prop="startTime" width="150" />
            <el-table-column label="结束时间" prop="endTime" width="150" />
          </el-table-column>
          <el-table-column prop="durationTime" label="时长" width="100">
            <template #default="scope">
              <el-text>
                <el-icon>
                  <Clock />
                </el-icon>
                {{ scope.row.durationTime }}
              </el-text>
            </template>
          </el-table-column>

          <el-table-column label="状态" width="120">
            <template #default="scope">
              <OvertimeStatusTag :status="scope.row.overtimeStatus * 1" />
            </template>
          </el-table-column>

          <el-table-column label="工作内容" width="350">
            <template #default="scope">
              <div class="remark-content">
                {{ scope.row.reason }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="流程" width="150">
            <template #default="scope">
              {{ scope.row.overtimeProcess }}
            </template>
          </el-table-column>
          <el-table-column />
          <el-table-column label="审批" width="220" fixed="right" v-if="!isHistoryData">
            <template #default="scope">
              <el-button link type="danger" size="small" :icon="Delete">删除</el-button>
              <el-button link type="success" @click="handleClickBtnUpdateOvertimePass(scope.row.id)" size="small" :icon="Select">通过</el-button>
              <el-button link type="warning" @click="handleClickBtnUpdateOvertimeNoPass(scope.row.id)" size="small" :icon="CloseBold">不通过</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </ContainerLayout>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, watch, nextTick } from 'vue'
import ContainerLayout from '../layout/ContainerLayout.vue'
import * as utils from '../utils'
// import http from '../http'
import { useDeptStore, useProjectssStore, useUsersStore } from '../stores'
import { Refresh, Search, Clock, Select, CloseBold, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { overtimeStatusEnum, overtimeStatus } from '../definitions/status'
import TimeSlotDatePicker from '../layout/FormTableLayout/TimeSlotDatePicker.vue'
import ExcelExportButton from '../layout/ButtonToolbar/ExcelExportButton.vue'
import OvertimeStatusTag from '../components/Overtime/OvertimeStatusTag.vue'
import api from '../api'

const isHistoryData = ref(false)
const deptList = ref(useDeptStore().getAllState())
const deptProps = ref({ multiple: true, label: 'deptName', value: 'deptId' })
const tableData = ref<any[]>([])
const tableColumnDate = ref<any[]>([])
const tableWrap = ref<HTMLElement | null>(null)
const tableHeight = ref(500)
const multipleSelection = ref<any[]>([])
const exportTableData = ref<any[]>([])
const exportHeaderParams = [
  { title: '姓名', value: 'userName', width: 20 },
  { title: '项目', value: 'projectName', width: 20 },
  {
    title: '时段',
    children: [
      { title: '开始时间', value: 'startTime', width: 25 },
      { title: '结束时间', value: 'endTime', width: 25 },
    ],
  },
  { title: '时长', value: 'durationTime', width: 20 },
  { title: '状态', value: 'overtimeStatus', width: 25 },
  { title: '工作内容', value: 'remark', width: 30 },
]
const selectable = (row: any) => row.status !== 1

const projectList = ref<Array<{ id: number; code: string; cname: string }>>(useProjectssStore().getAllState() as any)
const queryForm = reactive({
  user: '',
  projectId: null,
  date: [] as Date[],
  deptIds: [] as any[] | number[],
  overtimeStatus: null,
})

const overtimeStatusOptions = ref<any[]>([])

Object.keys(overtimeStatusEnum).map((value: any) => {
  const label = overtimeStatusEnum[value]
  if (typeof label === 'string' && value !== '3') {
    overtimeStatusOptions.value.push({
      label,
      value,
    })
  }
})

/**
 * 获取考勤分类列表
 *
 * @returns {Promise<void>}
 */
const getClockinCategoryList = async () => {
  const [start, end] = queryForm.date
  // 设置 table 列
  tableColumnDate.value = utils.generateDates(start, end)

  // 设置查询参数
  const params = {
    // deptId: useUsersStore().user.deptId,
    pageSize: 99999,
    startTime: utils.formatDate(start, 'yyyy-MM-dd'),
    endTime: utils.formatDate(end, 'yyyy-MM-dd'),
    approvalUserName: useUsersStore().getAllState().username,
  }
  if (queryForm.overtimeStatus) {
    Object.assign(params, { overtimeStatus: queryForm.overtimeStatus })
  }
  if (queryForm.projectId) {
    Object.assign(params, { projectId: queryForm.projectId })
  }
  if (queryForm.user !== '') {
    Object.assign(params, { userName: queryForm.user })
  }

  const funNames = isHistoryData.value ? 'searchHistoryByUser' : 'searchByUser'
  const { rows } = await api.Overtime[funNames](params)
  // console.log('rows', rows)
  // const { rows } = await http({
  //   method: 'GET',
  //   path: '/dev-api/oa/overtime/list',
  //   params,
  // })
  if (rows) {
    tableData.value = rows
    rows.forEach((e: any) => {
      exportTableData.value.push({ ...e, overtimeStatus: overtimeStatus[e.overtimeStatus][0] })
    })
  }
}
/**
 * 重置表单
 *
 * 重置查询表单的所有字段到初始状态，包括用户、项目ID、日期范围、部门ID数组和时间日志类别
 */
const resetForm = () => {
  tableData.value = []
  const [start, end] = utils.getDateRangeByDate(utils.shortcutsType.本月) as Date[]
  queryForm.user = ''
  queryForm.projectId = null
  queryForm.date = [start, end]
  queryForm.deptIds = [] as string[] | number[]
  queryForm.overtimeStatus = null
  handleClickBtnSubmit()
}
/**
 * 处理点击提交按钮的事件
 *
 * 异步调用获取打卡分类列表的函数
 */
const handleClickBtnSubmit = async () => {
  await getClockinCategoryList()
}

/**
 * 处理点击重置按钮的事件
 *
 * 调用 resetForm 函数重置表单
 */
const handleClickBtnReset = async () => {
  await resetForm()
}

const getProjectName = (id: any) => {
  const item = projectList.value.find((item) => item.id == id)
  return item?.cname || ''
}

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

/**
 * 更新加班申请状态按钮点击事件处理函数
 *
 * @param status 要更新的加班状态码
 * @param row 指定的加班记录，若未提供则默认使用多选选中的记录
 * @returns 无返回值
 */
const handleClickBtnUpdateOvertimeStatus = async (status: number, row: any | null = null) => {
  // 已作废 又好了
  let ids: any[] = []
  if (!row) {
    if (multipleSelection.value.length === 0) return ElMessage.warning('请选择要操作的记录')
    ids = multipleSelection.value.map((obj) => obj.id)
  } else {
    ids = [row.id]
  }
  //
  // const { code } = await api.Overtime.updateOvertimePass(id)

  const reqArr: any[] = []
  switch (status) {
    case overtimeStatusEnum.部门领导通过:
      ElMessageBox.confirm(`共 ${ids.length} 条，确定通过吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          ids.forEach((e) => {
            reqArr.push(api.Overtime.updateOvertimePass(e))
          })
          const promisRes = await Promise.all(reqArr)
          if (reqArr.length) {
            const allSuccess = promisRes.every((res) => res.code === 200)
            if (allSuccess) {
              ElMessage.success('操作成功')
              await handleClickBtnSubmit()
            }
          }
        })
        .catch(async () => {})
      break
    case overtimeStatusEnum.已驳回:
      ElMessageBox.confirm(`共 ${ids.length} 条，确定不通过吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          ids.forEach((e) => {
            reqArr.push(api.Overtime.updateOvertimeNoPass(e))
          })
          const promisRes = await Promise.all(reqArr)
          if (reqArr.length) {
            const allSuccess = promisRes.every((res) => res.code === 200)
            if (allSuccess) {
              ElMessage.success('操作成功')
              await handleClickBtnSubmit()
            }
          }
        })
        .catch(async () => {})
      break
  }
}
/**
 * 处理点击按钮更新加班审批状态的函数
 *
 * @param id 加班申请的ID
 */
const handleClickBtnUpdateOvertimePass = (id: number) => {
  ElMessageBox.confirm('确定通过吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code } = await api.Overtime.updateOvertimePass(id)

      if (code == 200) {
        ElMessage.success('操作成功')
        // 设置通知为未读状态，并刷新页面
        sessionStorage.setItem('OVERTIME_ISCHECKED', '0')
        await handleClickBtnSubmit()
      }
    })
    .catch(async () => {})
}
/**
 * 点击按钮处理不通过加班申请的确认操作
 *
 * @param id 加班申请的ID
 */
const handleClickBtnUpdateOvertimeNoPass = (id: number) => {
  ElMessageBox.confirm('确定不通过吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code } = await api.Overtime.updateOvertimeNoPass(id)

      if (code == 200) {
        ElMessage.success('操作成功')
        await handleClickBtnSubmit()
      }
    })
    .catch(async () => {})
}
watch(
  () => isHistoryData.value,
  async () => {
    await handleClickBtnSubmit()
  }
)
onMounted(async () => {
  await handleClickBtnReset()
  // await handleClickBtnSubmit()

  nextTick(() => {
    const tableWrapElement = tableWrap.value
    if (tableWrapElement) {
      // 设置表格高度
      tableHeight.value = tableWrapElement.offsetHeight
    }
  })
})
</script>
<style lang="scss" scoped>
.overitem-list {
  display: flex;
  flex-direction: column;
  .form-container {
    display: flex;
    justify-content: flex-start;
  }
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .table-wrap {
      flex: 1;
    }
  }
  .button-toolbar {
    margin-bottom: 18px;
  }
  .table-header-cell {
    writing-mode: vertical-lr;
  }
  .remark-content {
    width: 100%;
    height: 100%;
    white-space: pre-line;
  }
}
</style>
